package ge.telasi.tasks.model;

import java.io.Serializable;
import java.util.Calendar;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * This is a superclass of the entities which are required to save their
 * create/update dates and their current status.
 *
 * @author dimitri
 */
@MappedSuperclass
public abstract class Modifiable implements Serializable {

	@Column(name = "created")
	@Temporal(value = TemporalType.TIMESTAMP)
	private Calendar created;
	@Column(name = "modified")
	@Temporal(value = TemporalType.TIMESTAMP)
	private Calendar modified;
	@Column(name = "status")
	private int status;

	public Calendar getCreated() {
		return created;
	}

    protected void setCreated(Calendar created) {
        this.created = created;
    }

	public Calendar getModified() {
		return modified;
	}

    protected void setModified(Calendar modified) {
        this.modified = modified;
    }

	public boolean isActive() {
		return status == 1;
	}

	public void setActive(boolean active) {
		status = active ? 1 : 0;
	}

	/**
	 * This method is called by entity manager before persisting Modifiable.
	 * Public modifier of this method is very important: if you use private or
	 * protected modifiers child classes can not use this methods as life-cycle
	 * method listener.
	 */
	@PrePersist
	public void prePersist() {
		created = Calendar.getInstance();
		modified = Calendar.getInstance();
	}

	/**
	 * This method is called by entity manager before updating Modifiable.
	 *
	 * @see #prePersist()
	 */
	@PreUpdate
	public void preUpdate() {
		modified = Calendar.getInstance();
	}

    /**
     * Clone utility method.
     */
    protected void cloneCommons(Modifiable m) {
        m.setActive(isActive());
        m.created = created;
        m.modified = modified;
    }

}
